import axios from 'axios'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    token: `Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijg5N2M3YTA5LTljNWMtNGVkYi04NzA3LTE4Mjg5MGEyNmQzYSJ9.y7dd0Rf50g-Ecvi9vBO0iaGyJw57hNK4k_qX5mfzCU_xIyaM3_Rxhvcsz5xzVvMBqgfdhVkRvlDg32QwExAjDw`
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 合并默认 headers 和请求时传入的 headers
    config.headers = {
      ...service.defaults.headers,
      ...config.headers
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code === 200) {
      return res.data
    }
    console.error('请求错误：', res.message)
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  (error) => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

export default service
